//
//  CreateBookView.m
//  Bespoke
//
//  Created by Cheng on 13/1/4.
//
//

#import "CreateBookView.h"
#import "RequestAPIFunction.h"
#import "Split.h"
#import "GDataXMLNode.h"

#define KEYBOARDHEIGHT 360

#define MODIFYMYBOARD_API @"http://54.235.166.43/BeSpokeAPI/MyBoard/ModifyMyBoard.php"

@implementation CreateBookView
@synthesize AMB_MyBoard, BK_En_object, Tf_BookName;
@synthesize delegate;

-(IBAction)CancelPressed:(id)sender {
    
    [Tf_BookName resignFirstResponder];
    [self.delegate uiViewCancel];
}

-(IBAction)CreatePressed:(id)sender {
    
    if ([Tf_BookName.text isEqualToString:@""]) {
        UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please Input Book Name." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [AlertView show];
        return;
    }
    
    [Tf_BookName resignFirstResponder];
    
    NSData *responseData =
    [RequestAPIFunction XML_PostRequest:[NSString stringWithFormat:@"<AccountInfo UserName=\"%@\" Level=\"\" Name=\"%@\" Action=\"Create\"><Board ID=\"0\" Name=\"%@\" /></AccountInfo>",
                                         self.BK_En_object.userName,
                                         self.BK_En_object.fullName,
                                         [Tf_BookName.text SymbolParseString]]
                              urlString:MODIFYMYBOARD_API];
    
    //No Network Connection or time out.
    if (responseData == nil)
        return;
    
    NSError *error;
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:responseData options:0 error:&error];
    
    //Check to upload is success.
    if ([[doc nodesForXPath:@"//Success" error:&error] count]!=0) {
        
        NSArray *Array_Success = [doc nodesForXPath:@"//Success" error:nil];
        
        int BoardID = [[[[Array_Success objectAtIndex:0] attributeForName:@"BoardID"] stringValue] intValue];
    
        AccountBoard *AB_NilBoard = [[AccountBoard alloc] BoardID:BoardID name:Tf_BookName.text ShareGroup:@""];
        [AMB_MyBoard.BoardArray addObject:AB_NilBoard];
        
        [self.delegate ViewDidCreated];
    }
}

#pragma mark - UITextFieldDelegate

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    
    self.frame = CGRectMake(self.frame.origin.x,
                            self.superview.bounds.size.height-KEYBOARDHEIGHT-self.frame.size.height,
                            self.frame.size.width,
                            self.frame.size.height);
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
    self.center = CGPointMake(self.superview.bounds.size.width/2,
                              self.superview.bounds.size.height/2);
    
}

@end
